package com.company.project.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.redismq.ZSetVer;
import com.company.project.common.utils.*;
import com.company.project.entity.*;
import com.company.project.mapper.*;
import com.company.project.service.*;
import com.company.project.vo.req.TSeatsEntityOperationReqVO;
import com.google.common.collect.Lists;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service("tSeatsService")
@Slf4j
public class TSeatsServiceImpl extends ServiceImpl<TSeatsMapper, TSeatsEntity> implements TSeatsService {

    @Autowired
    public TSeatsMapper tSeatsMapper;
    @Autowired
    public TXiaohaoMapper xiaohaoMapper;
    @Resource
    private UserService userService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysDictDetailMapper sysDictDetailMapper;
    @Resource
    private SysDictMapper sysDictMapper;
    @Autowired
    private SysSmscodeMapper sysSmscodeMapper;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private TFzsczLogService tFzsczLogService;
    @Autowired
    private TUserLogService tUserLogService;
    @Autowired
    private TCzjlService tCzjlService;
    @Resource
    private TZjhmglMapper zjhmglMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private DeptService deptService;
    @Resource
    private SysRoleDeptService sysRoleDeptService;
    @Autowired
    private TCallbakMapper callbakMapper;

    @Autowired
    private TThjlmxMapper thjlmxMapper;
    @Autowired
    public TThrbMapper thrbMapper;
    @Autowired
    private THwtjMapper hwtjMapper;

    @Autowired
    private THwtjFzsMapper hwtjFzsMapper;
    @Resource
    private TGzszMapper tGzszMapper;

    @Autowired
    private TZjhmglService tZjhmglService;
    @Autowired
    private TMiddlenumService tMiddlenumService;
    @Autowired
    private TMiddlenumMapper tMiddlenumMapper;
    @Autowired
    private TXiaohaoMapper tXiaohaoMapper;
   @Autowired
    private TKaiguanMapper tKaiguanMapper;
    @Autowired
    public TBacklistMapper backlistMapper;
    @Resource
    public TCallbakTaskService tCallbakTaskService;
    @Resource
    public RedisService redisService;
    public final static String RS_ZS_MQ_ME = "consumerDelayMessage:";

    @Autowired
    private ZSetVer zSetVer;

    @Override
    public DataResult addTSeats(TSeatsEntityOperationReqVO vo) {
        try {
            if (Func.isEmpty(vo.getRole())) {
                throw new BusinessException("请选择角色！");
            }
            TCzjlEntity tCzjl = new TCzjlEntity();
            tCzjl.setUserid(vo.getAccount());
            tCzjl.setGsmc(vo.getCorporatename());
            tCzjl.setCzqk("支出");
            tCzjl.setCzTime(new Date());

            //账号日志
            TUserLogEntity tUserLog = new TUserLogEntity();
            tUserLog.setStart("0");
            tUserLog.setUsername(vo.getContacts());
            tUserLog.setUserid(vo.getAccount());
            tUserLog.setPhone(vo.getPhone());
            tUserLog.setCompany(vo.getCorporatename());
            tUserLog.setEndtime(new Date());
            //获取当前操作人
            //通过access_token拿userId
            String userId = httpSessionService.getCurrentUserId();
            SysUser user = userService.getById(userId);
            tUserLog.setCzry(user.getUsername());
            //部门id  0 代表为管理员
            String deptId = user.getDeptId();

            Date currentDate = new Date();
            Date tcczTime = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            //套餐重置时间
            Date dqTime = calendar.getTime();
            if (vo.getEndtime() != null) {
                calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(vo.getEndtime())*30+1);
                dqTime = calendar.getTime();
            }
            Calendar calendarcz = Calendar.getInstance();
            calendarcz.setTime(currentDate);
            calendarcz.add(Calendar.DAY_OF_MONTH, 31);
            //套餐重置时间
            tcczTime = calendarcz.getTime();
            if (Func.equals("0",deptId)) {
                //创建用户
                SysUser sysUser = new SysUser();
                sysUser.setUsername(vo.getAccount());
                sysUser.setPassword(vo.getPassword());
                sysUser.setNickName(vo.getContacts());
                sysUser.setDeptId(vo.getDept());
                List<String> roles = new ArrayList<>();
                roles.add(vo.getRole());
                sysUser.setRoleIds(roles);
                SysUser sysUserVo = userService.addUser(sysUser);

                SysRole sysRole = sysRoleMapper.selectById(vo.getRole());

                //添加坐席
                TSeatsEntity tSeats = new TSeatsEntity();
                tSeats.setRole(vo.getRole());
                tSeats.setAccountid(sysUserVo.getId());
                tSeats.setContacts(vo.getContacts());
                tSeats.setCorporatename(vo.getCorporatename());
                tSeats.setContacts(vo.getContacts());
                tSeats.setPhone(vo.getPhone());
                tSeats.setAmount(vo.getAmount());
                tSeats.setEndtime(vo.getEndtime());

                tSeats.setLine(vo.getLine());
                tSeats.setSeats(vo.getSeats());
                tSeats.setMode(vo.getMode());
                tSeats.setSalesname(vo.getSalesname());
                tSeats.setState("0");//默认状态
                //套餐模式 1:坐席模式  2: 套餐模式
                if (Func.equals(vo.getTcType1(),"1")){
                    tSeats.setTcType(vo.getTcType1());
                    tSeats.setResidue(vo.getResidue1());
                    tCzjl.setFzs(vo.getResidue1());
                } else if (Func.equals(vo.getTcType2(),"2")){
                    tCzjl.setCzqk("套餐支出");
                    tSeats.setTcType(vo.getTcType2());
                    tSeats.setResidue(vo.getResidue2());
                    tSeats.setTcfzs(vo.getResidue2());
                    tCzjl.setFzs(vo.getResidue2());
                }

                //新增总经理角色添加总经理部门
                if (Func.equals("总经理",sysRole.getName())) {
                    List<TGzszEntity> tGzszEntities = tGzszMapper.selectList(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeats.getCorporatename()));
                    if (!Func.isEmpty(tGzszEntities)){
                        throw new BusinessException("添加坐席失败 ，公司已存在！");
                    }
                    SysDept deptVo = new SysDept();
                    deptVo.setName(tSeats.getCorporatename());
                    deptVo.setUserid(sysUserVo.getId());
                    deptVo.setPid("0");
                    deptVo.setPidName("管理员");
                    //添加部门
                    deptService.addDept(deptVo);
                    tSeats.setDept(deptVo.getId());//设置坐席部门ID
                    SysRoleDeptEntity  roleDept = new SysRoleDeptEntity();
                    roleDept.setRoleId(sysRole.getId());
                    roleDept.setDeptId(deptVo.getId());
                    //添加关联关系
                    sysRoleDeptService.save(roleDept);

                    //设置成公司管理员
                    tSeats.setGsgl("1");
                    //设置公海规则
                    TGzszEntity tGzsz = new TGzszEntity();
                    tGzsz.setSsgs(tSeats.getCorporatename());

                    tGzszMapper.insert(tGzsz);

                } else if (Func.equals("代理商",sysRole.getName())) {
                    SysDept deptVo = new SysDept();
                    deptVo.setName(tSeats.getCorporatename());
                    deptVo.setUserid(sysUserVo.getId());
                    deptVo.setPid("0");
                    deptVo.setPidName("管理员");
                    //添加部门
                    deptService.addDept(deptVo);
                    tSeats.setDept(deptVo.getId());//设置坐席部门ID
                    SysRoleDeptEntity  roleDept = new SysRoleDeptEntity();
                    roleDept.setRoleId(sysRole.getId());
                    roleDept.setDeptId(deptVo.getId());
                    //添加关联关系
                    sysRoleDeptService.save(roleDept);
                }
                //话务统计分钟数 t_hwtj_fzs
                THwtjFzsEntity fzsEntity = hwtjFzsMapper.selectOne(Wrappers.<THwtjFzsEntity>lambdaQuery().eq(THwtjFzsEntity::getCompany, tSeats.getCorporatename()));
                if (fzsEntity != null){
                    fzsEntity.setFzsze(tSeats.getResidue());//分钟总数
                    fzsEntity.setSyfzs(tSeats.getResidue());//剩余分钟数
                    hwtjFzsMapper.updateById(fzsEntity);
                }else {
                    THwtjFzsEntity tHwtjFzs = new THwtjFzsEntity();
                    tHwtjFzs.setCompany(tSeats.getCorporatename());//公司名称
                    tHwtjFzs.setFzsze(tSeats.getResidue());//分钟总数
                    tHwtjFzs.setSyfzs(tSeats.getResidue());//剩余分钟数
                    List<THwtjFzsEntity> list = new ArrayList<>();
                    list.add(tHwtjFzs);
                    hwtjFzsMapper.insertList(list);

                }

                //话务统计 t_hwtj
                THwtjEntity hwtj = hwtjMapper.selectOneByCorporatename(tSeats.getCorporatename());
                if (hwtj == null) {
                    hwtj = new THwtjEntity();
                    hwtj.setCompany(tSeats.getCorporatename());//公司名称
                    hwtj.setFzsze(tSeats.getResidue());//分钟总数
                    hwtj.setSyfzs(tSeats.getResidue());//剩余分钟数
                }

                hwtj.setBscs("0");
                hwtj.setJts("0");
                hwtj.setJfsc("0");//计费时长
                hwtj.setThsc("0");//通话时长
                hwtj.setXs(tSeats.getSalesname());//销售
                hwtj.setDate(new Date());
                hwtj.setOrgname(tSeats.getDept());
                hwtjMapper.insert(hwtj);

                //设置sys_user dept
                sysUserVo.setDeptId(tSeats.getDept());
                sysUserMapper.updateById(sysUserVo);

                if (Func.equals(vo.getTcType2(),"2")){
                    tSeats.setTccztime(tcczTime);
                }

                tSeats.setCreateuser(user.getUsername());
                tSeats.setCreatetime(new Date());
                tSeats.setPassword(vo.getPassword());

                tSeats.setApkid(vo.getApkid());
                tSeats.setAk(vo.getAk());
                tSeats.setSk(vo.getSk());
                tSeats.setDqtime(dqTime);

                tSeatsMapper.insert(tSeats);

                tUserLogService.save(tUserLog);
                tCzjlService.save(tCzjl);

            } else {
                //当前登录人坐席
                LambdaQueryWrapper<TSeatsEntity> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TSeatsEntity::getAccountid, user.getId());
                TSeatsEntity tSeatsEntity = tSeatsMapper.selectOne(queryWrapper);
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TSeatsEntity::getCorporatename,tSeatsEntity.getCorporatename());
                //本公司坐席数量
                Integer integer = tSeatsMapper.selectSeatCount(tSeatsEntity.getCorporatename());
                if(Func.isEmpty(tSeatsEntity.getSeats())) throw new BusinessException("添加坐席失败 ，坐席总数量异常！");
                Integer seats = Integer.valueOf(tSeatsEntity.getSeats());//坐席总数量
                SysRole sysRole = sysRoleMapper.selectById(vo.getRole());

                Integer residue = tSeatsEntity.getResidue();//创建人剩余分钟数
                if (integer < seats || Func.equals("总经理",sysRole.getName()) || Func.equals("总监",sysRole.getName())) {
                    //创建用户
                    SysUser sysUser = new SysUser();
                    sysUser.setUsername(vo.getAccount());
                    sysUser.setPassword(vo.getPassword());
                    sysUser.setDeptId(vo.getDept());//部门
                    sysUser.setNickName(vo.getContacts());
                    List<String> roles = new ArrayList<>();
                    roles.add(vo.getRole());
                    sysUser.setRoleIds(roles);
                    SysUser sysUserVo = userService.addUser(sysUser);


                    //添加坐席
                    TSeatsEntity tSeats = new TSeatsEntity();
                    String corporatename = Func.isEmpty(vo.getCorporatename())?tSeatsEntity.getCorporatename():vo.getCorporatename();
                    tSeats.setRole(vo.getRole());
                    tSeats.setAccountid(sysUserVo.getId());
                    tSeats.setContacts(vo.getContacts());
                    tSeats.setCorporatename(corporatename);
                    tSeats.setContacts(vo.getContacts());
                    tSeats.setPhone(vo.getPhone());
                    tSeats.setAmount(tSeatsEntity.getAmount());
                    tSeats.setEndtime(tSeatsEntity.getEndtime());
                    if (Func.equals(vo.getTcType2(),"2")){
                        tSeats.setTccztime(tcczTime);
                    }
                    //继承线路
                    tSeats.setLine(tSeatsEntity.getLine());
//                    tSeats.setSeats(vo.getSeats());
                    tSeats.setMode(tSeatsEntity.getMode());
                    tSeats.setSalesname(tSeatsEntity.getSalesname());
                    tSeats.setState("0");//默认状态

                    //套餐模式 1:坐席模式  2: 套餐模式
                    if (Func.equals(vo.getTcType1(),"1")){
                        tSeats.setTcType(vo.getTcType1());
                        tSeats.setResidue(vo.getResidue1());
                        tCzjl.setFzs(vo.getResidue1());
                        if (vo.getEndtime() != null) {
                            calendar.add(Calendar.DAY_OF_MONTH, 31);
                        }
                        //重置时间
                        tcczTime = calendar.getTime();
                    } else if (Func.equals(vo.getTcType2(),"2")){
                        tCzjl.setCzqk("套餐支出");
                        tSeats.setTcType(vo.getTcType2());
                        tSeats.setResidue(vo.getResidue2());//剩余分钟数
                        tSeats.setTcfzs(vo.getResidue2());//套餐分钟数
                        tCzjl.setFzs(vo.getResidue2());

                    } else {
                        //继承套餐模式
                        tSeats.setTcType(tSeatsEntity.getTcType());
                        tSeats.setResidue(tSeatsEntity.getResidue());
                        tSeats.setDqtime(tSeatsEntity.getDqtime());
                        tSeats.setTccztime(tSeatsEntity.getTccztime());

                    }

//                    tCzjl.setFzs(tSeatsEntity.getResidue());
                    tSeats.setCreateuser(user.getUsername());
                    //新增总经理角色添加总经理部门
                    if (Func.equals("总经理",sysRole.getName())) {
                        List<TGzszEntity> tGzszEntities = tGzszMapper.selectList(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeats.getCorporatename()));
                        if (!Func.isEmpty(tGzszEntities)){
                            throw new BusinessException("添加坐席失败 ，公司已存在！");
                        }
                        SysDept byId = deptService.getById(user.getDeptId());
                        SysDept deptVo = new SysDept();
                        deptVo.setName(tSeats.getCorporatename());
                        deptVo.setUserid(sysUserVo.getId());
                        deptVo.setPid(user.getDeptId());
                        deptVo.setPidName(byId.getName());
                        //添加部门
                        deptService.addDept(deptVo);
                        tSeats.setDept(deptVo.getId());//设置坐席部门ID
                        SysRoleDeptEntity  roleDept = new SysRoleDeptEntity();
                        roleDept.setRoleId(sysRole.getId());
                        roleDept.setDeptId(deptVo.getId());
                        //添加关联关系
                        sysRoleDeptService.save(roleDept);
                        tSeats.setDqtime(dqTime);

                        //设置成公司管理员
                        tSeats.setGsgl("1");

                        //变更代理商 剩余分钟数
                        if (tSeatsEntity.getResidue()-tSeats.getResidue() > 0) {
                            tSeatsEntity.setResidue(tSeatsEntity.getResidue()-tSeats.getResidue());
                            tSeatsMapper.updateById(tSeatsEntity);
                        } else {
                            throw new BusinessException("添加坐席失败 ，剩余分钟数不足！");
                        }

                        //设置公海规则
                        TGzszEntity tGzsz = new TGzszEntity();
                        tGzsz.setSsgs(tSeats.getCorporatename());

                        tGzszMapper.insert(tGzsz);

                    } else {
                        SysRoleDeptEntity  roleDept = new SysRoleDeptEntity();
                        roleDept.setRoleId(sysRole.getId());
                        roleDept.setDeptId(vo.getDept());
                        //添加关联关系
                        sysRoleDeptService.save(roleDept);
                        tSeats.setDqtime(tSeatsEntity.getDqtime());
                    }

                    //部门
                    if (Func.isNotEmpty(vo.getDept())) {
                        tSeats.setDept(vo.getDept());
                    }
                    //话务统计分钟数 t_hwtj_fzs
                    THwtjFzsEntity fzsEntity = hwtjFzsMapper.selectOne(Wrappers.<THwtjFzsEntity>lambdaQuery().eq(THwtjFzsEntity::getCompany, tSeats.getCorporatename()));
                    if (fzsEntity != null){
                        fzsEntity.setFzsze(tSeats.getResidue());//分钟总数
                        fzsEntity.setSyfzs(tSeats.getResidue());//剩余分钟数
                        hwtjFzsMapper.updateById(fzsEntity);
                    }else {
                        THwtjFzsEntity tHwtjFzs = new THwtjFzsEntity();
                        tHwtjFzs.setCompany(tSeats.getCorporatename());//公司名称
                        tHwtjFzs.setFzsze(tSeats.getResidue());//分钟总数
                        tHwtjFzs.setSyfzs(tSeats.getResidue());//剩余分钟数
                        List<THwtjFzsEntity> list = new ArrayList<>();
                        list.add(tHwtjFzs);
                        hwtjFzsMapper.insertList(list);
                    }
                    //话务统计 t_hwtj
                    THwtjEntity hwtj = hwtjMapper.selectOneByCorporatename(tSeats.getCorporatename());
                    if (hwtj == null) {
                        hwtj = new THwtjEntity();
                        hwtj.setCompany(tSeats.getCorporatename());//公司名称
                        hwtj.setFzsze(tSeats.getResidue());//分钟总数
                        hwtj.setSyfzs(tSeats.getResidue());//剩余分钟数
                    }
                    hwtj.setBscs("0");
                    hwtj.setJts("0");
                    hwtj.setJfsc("0");//计费时长
                    hwtj.setThsc("0");//通话时长
                    hwtj.setXs(tSeats.getSalesname());//销售
                    hwtj.setDate(new Date());
                    hwtj.setOrgname(tSeats.getDept());
                    hwtjMapper.insert(hwtj);


                    //设置sys_user dept
                    sysUserVo.setDeptId(tSeats.getDept());
                    sysUserMapper.updateById(sysUserVo);

                    tSeats.setCreatetime(new Date());
                    tSeats.setPassword(vo.getPassword());

//                    tSeats.setApkid(vo.getApkid());
//                    tSeats.setAk(vo.getAk());
//                    tSeats.setSk(vo.getSk());

                    if (!Func.isEmpty(tSeats.getResidue()) && Integer.valueOf(residue) < Integer.valueOf(tSeats.getResidue())) {
                        throw new BusinessException("添加坐席失败，剩余分钟数不足，请联系管理员！");
                    }
                    tSeatsMapper.insert(tSeats);
                    if (Func.equals("主管",sysRole.getName()) || Func.equals("员工",sysRole.getName())){
                        TZjhmglEntity tZjhmglEntity = new TZjhmglEntity();
                        tZjhmglEntity.setCompany(tSeats.getCorporatename());
                        tZjhmglEntity.setZjr(user.getUsername());
                        tZjhmglEntity.setAddtime(new Date());
                        tZjhmglEntity.setStart("1");//状态 1:正常 2：禁用
                        tZjhmglEntity.setZjhm(tSeats.getPhone());
                        tZjhmglEntity.setUserid(vo.getAccount());
                        tZjhmglService.save(tZjhmglEntity);
                    }
                } else {
                    throw new BusinessException("添加坐席失败，座席数已满，请联系管理员！");
                }
                tUserLogService.save(tUserLog);
                if(Func.equals("总经理",sysRole.getName())) tCzjlService.save(tCzjl);
            }
        } catch (BusinessException e) {
            e.printStackTrace();
            return DataResult.fail(e.getMessage());
        }
        return DataResult.success();
    }

    @Override
    public IPage<TSeatsEntity> pageData(Page page, TSeatsEntityOperationReqVO vo) {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        SysUser sysUser = userService.getById(userId);
        List<String> sysRoleNames = roleService.getRoleNames(userId);
        String roleName = sysRoleNames.get(0);//自己的角色/
        IPage<TSeatsEntity> iPage = tSeatsMapper.pageData(page,vo,sysUser,roleName);
        return iPage;
    }

    @Override
    public DataResult infoData() {
        try {
            Map<String, Object> map = new HashMap<>();

            SysDictEntity sysDict = sysDictMapper.selectOne(Wrappers.<SysDictEntity>lambdaQuery().eq(SysDictEntity::getName, "smfs"));
            LambdaQueryWrapper<SysDictDetailEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(SysDictDetailEntity::getDictId, sysDict.getId());
            wrapper.orderByAsc(SysDictDetailEntity::getSort);
            List<SysDictDetailEntity> smfss = sysDictDetailMapper.selectList(wrapper);

            sysDict = sysDictMapper.selectOne(Wrappers.<SysDictEntity>lambdaQuery().eq(SysDictEntity::getName, "line"));
            wrapper = Wrappers.lambdaQuery();
            wrapper.eq(SysDictDetailEntity::getDictId, sysDict.getId());
            wrapper.orderByAsc(SysDictDetailEntity::getSort);
            List<SysDictDetailEntity> lines = sysDictDetailMapper.selectList(wrapper);

            String userId = httpSessionService.getCurrentUserId();
            SysUser sysUser = userService.getById(userId);

            //公司名称
            QueryWrapper<TSeatsEntity> co = new QueryWrapper();
            co.select("distinct corporatename");
//            co.eq(TSeatsEntity::getCreateuser,sysUser.getUsername());
            List<String> corporatenames = tSeatsMapper.selectCorp(sysUser);
//            List<String> corporatenames = tSeatsMapper.selectList(co).stream().map(m -> m.getCorporatename()).collect(Collectors.toList());

            //销售
            QueryWrapper<TSeatsEntity> sa = new QueryWrapper();
            sa.select("distinct salesname");
            List<String> salesnames = tSeatsMapper.selectList(sa).stream().map(m -> m.getSalesname()).collect(Collectors.toList());
            map.put("smfss",smfss);
            map.put("lines",lines);
            map.put("corporatenames",corporatenames);
            map.put("salesnames",salesnames);
            return DataResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("字典项异常，请联系管理员！");
        }
    }

    @Override
    public DataResult updateFzs(TSeatsEntityOperationReqVO vo) {
        try{
            String mobile = vo.getMobile();
            String smscode = vo.getSmscode();
//            //效验验证码
//            SysSmscodeEntity sysSmscode = sysSmscodeMapper.selectOne(Wrappers.<SysSmscodeEntity>lambdaQuery()
//                    .eq(SysSmscodeEntity::getPhone, mobile)
//                    .eq(SysSmscodeEntity::getSmscode, smscode)
//            );
//            if (Func.isNull(sysSmscode)) {
//                return DataResult.fail("验证码错误");
//            }
//
//            Date time = sysSmscode.getTime();
//            Date date = new Date();
//            // 计算时间差（毫秒）
//            long timeDifference = date.getTime() - time.getTime();
//            long l = timeDifference / 1000;
//            if (l > 60) {
//                return DataResult.fail("验证码超时");
//            }
            //更改分钟数据
            TSeatsEntity tSeats1 = tSeatsMapper.selectById(vo.getId());
            SysUser byId = userService.getById(tSeats1.getAccountid());
            SysUser userInfo = userService.getUserInfo();//当前操作人
            TSeatsEntity tSeatsDQ = userService.getTSeats();//当前坐席
            List<String> sysRoleNames = roleService.getRoleNames(userInfo.getId());
            String roleName = sysRoleNames.get(0);//自己的角色/
            //充值记录
            TCzjlEntity tCzjl = new TCzjlEntity();
            tCzjl.setUserid(byId.getUsername());//账号
            tCzjl.setGsmc(tSeats1.getCorporatename());
            tCzjl.setCzTime(new Date());
            tCzjl.setFzs(vo.getFzs());
            if(Func.equals("1",vo.getCztype())){//操作类型  增加
                tCzjl.setCzqk("支出");
                tSeats1.setResidue(Integer.valueOf(tSeats1.getResidue())+Integer.valueOf(vo.getFzs()));
                //话务统计 t_hwtj
                THwtjEntity hwtj = hwtjMapper.selectOneByCorporatename(tSeats1.getCorporatename());
                hwtj.setId("");
                hwtj.setCompany(tSeats1.getCorporatename());//公司名称
                Integer fzsze = hwtj.getFzsze();
                fzsze = fzsze == null ? 0 :fzsze;
                hwtj.setFzsze(fzsze+vo.getFzs());//分钟总数
                hwtj.setSyfzs(hwtj.getSyfzs()+vo.getFzs());//剩余分钟数
                hwtj.setBscs("0");
                hwtj.setJts("0");
                hwtj.setJfsc("0");//计费时长
                hwtj.setThsc("0");//通话时长
                hwtj.setXs(tSeats1.getSalesname());//销售
                hwtj.setDate(new Date());
                hwtjMapper.insert(hwtj);

                //话务统计分钟数 t_hwtj_fzs
                THwtjFzsEntity fzsEntity = hwtjFzsMapper.selectOne(Wrappers.<THwtjFzsEntity>lambdaQuery().eq(THwtjFzsEntity::getCompany, tSeats1.getCorporatename()));
                if (fzsEntity != null){
                    fzsEntity.setFzsze(fzsEntity.getFzsze()+vo.getFzs());//分钟总数
                    fzsEntity.setSyfzs(fzsEntity.getSyfzs()+vo.getFzs());//剩余分钟数
                    hwtjFzsMapper.updateById(fzsEntity);
                }
                //代理商控制分钟数
                if (Func.equals("代理商",roleName)){
                    //变更代理商 剩余分钟数
                    if (Integer.valueOf(tSeatsDQ.getResidue())-Integer.valueOf(vo.getFzs()) > 0) {
                        tSeatsDQ.setResidue(tSeatsDQ.getResidue()-vo.getFzs());
                    } else {
                        return DataResult.fail("分钟数修改失败 ，剩余分钟书不足！");
                    }
                }


            } else if(Func.equals("2",vo.getCztype())){//操作类型  减少
                //代理商控制分钟数
                if (Func.equals("代理商",roleName)){
                    if (Integer.valueOf(tSeats1.getResidue())-Integer.valueOf(vo.getFzs()) < 0) {
                        return DataResult.fail("分钟数修改失败 ，剩余分钟书不足！");
                    }
                }
                tCzjl.setCzqk("回收");
                tSeats1.setResidue(Integer.valueOf(tSeats1.getResidue())-Integer.valueOf(vo.getFzs()));
                //话务统计 t_hwtj
                THwtjEntity hwtj = hwtjMapper.selectOneByCorporatename(tSeats1.getCorporatename());
                hwtj.setId("");
                hwtj.setCompany(tSeats1.getCorporatename());//公司名称
                hwtj.setFzsze(hwtj.getFzsze()-vo.getFzs());//分钟总数
                hwtj.setSyfzs(hwtj.getSyfzs()-vo.getFzs());//剩余分钟数
                hwtj.setBscs("0");
                hwtj.setJts("0");
                hwtj.setJfsc("0");//计费时长
                hwtj.setThsc("0");//通话时长
                hwtj.setXs(tSeats1.getSalesname());//销售
                hwtj.setDate(new Date());
                hwtjMapper.insert(hwtj);

                //话务统计分钟数 t_hwtj_fzs
                THwtjFzsEntity fzsEntity = hwtjFzsMapper.selectOne(Wrappers.<THwtjFzsEntity>lambdaQuery().eq(THwtjFzsEntity::getCompany, tSeats1.getCorporatename()));
                if (fzsEntity != null){
                    fzsEntity.setFzsze(fzsEntity.getFzsze()+vo.getFzs());//分钟总数
                    fzsEntity.setSyfzs(fzsEntity.getSyfzs()+vo.getFzs());//剩余分钟数
                    hwtjFzsMapper.updateById(fzsEntity);
                }

                //代理商控制分钟数
                if (Func.equals("代理商",roleName)){
                    tSeatsDQ.setResidue(Integer.valueOf(tSeatsDQ.getResidue())+Integer.valueOf(vo.getFzs()));
                }
            }
            //修改全公司的剩余分钟数
            String corporatename = tSeats1.getCorporatename();
            List<TSeatsEntity> tSeatsEntities = tSeatsMapper.selectList(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, corporatename));
            for (TSeatsEntity t : tSeatsEntities) {
                t.setResidue(tSeats1.getResidue());
                tSeatsMapper.updateById(t);
            }
            tSeatsMapper.updateById(tSeatsDQ);
            tCzjlService.save(tCzjl);
            return DataResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return DataResult.fail("编辑分钟数失败！");
        }

    }


    @Override
    public DataResult updateXf(TSeatsEntityOperationReqVO vo) {
        try {
            TSeatsEntity tSeatsEntity = tSeatsMapper.selectById(vo.getId());
            Date dqtime = tSeatsEntity.getDqtime();
            //判断是否到期
            Date now = new Date();
            if (now.getTime() <= dqtime.getTime() ) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dqtime);
                //套餐重置时间
                Date dqTime = calendar.getTime();
                if (vo.getXfyf() != null) {
                    calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(vo.getXfyf()) * 30);
                }
                tSeatsEntity.setDqtime(calendar.getTime());
                List<TSeatsEntity> tSeatsEntities = tSeatsMapper.selectList(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeatsEntity.getCorporatename()));
                for (TSeatsEntity t : tSeatsEntities) {
                    t.setDqtime(calendar.getTime());
                    tSeatsMapper.updateById(t);
                }
            } else {
                // 到期后从新计算  然后 重置分钟数
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(now);
                //套餐重置时间
                Date dqTime = calendar.getTime();
                if (vo.getXfyf() != null) {
                    calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(vo.getXfyf()) * 30);
                }
                tSeatsEntity.setDqtime(calendar.getTime());
                List<TSeatsEntity> tSeatsEntities = tSeatsMapper.selectList(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeatsEntity.getCorporatename()));
                for (TSeatsEntity t : tSeatsEntities) {
                    t.setDqtime(calendar.getTime());
                    tSeatsMapper.updateById(t);
                }

                //重置分钟数
                String accountid = tSeatsEntity.getAccountid();
                Integer residue = tSeatsEntity.getResidue();//剩余分钟
                Integer tcfzs = tSeatsEntity.getTcfzs();//套餐分钟数

                //话务统计 t_hwtj
                THwtjEntity hwtj = hwtjMapper.selectOneByCorporatename(tSeatsEntity.getCorporatename());
                Date nowData = new Date();
                if (nowData.equals(hwtj.getDate())) {
                    long timeInMillis = nowData.getTime(); // 转换为毫秒数
                    timeInMillis += 1000; // 加1秒（1000毫秒）
                    nowData.setTime(timeInMillis); // 更新时间
                }
                hwtj.setId("");
                hwtj.setCompany(tSeatsEntity.getCorporatename());//公司名称
                hwtj.setFzsze(hwtj.getFzsze()+tcfzs);//总分钟数
                hwtj.setSyfzs(tcfzs);//剩余分钟数
                hwtj.setBscs("0");
                hwtj.setJts("0");
                hwtj.setJfsc("0");//计费时长
                hwtj.setThsc("0");//通话时长
                hwtj.setXs(tSeatsEntity.getSalesname());//销售
                hwtj.setOrgname(tSeatsEntity.getDept());//所属部门
                hwtj.setLine(tSeatsEntity.getLine());//线路
                hwtj.setDate(nowData);
                String createuser = tSeatsEntity.getCreateuser();
                if (!Func.equals("guest",createuser)){//非管理员创建 就是代理商
                    hwtj.setDl(createuser);//代理商
                }
                hwtjMapper.insert(hwtj);
                log.info("话务统计:{}",hwtj.toString());

                //话务统计分钟数 t_hwtj_fzs
                THwtjFzsEntity fzsEntity = hwtjFzsMapper.selectOne(Wrappers.<THwtjFzsEntity>lambdaQuery().eq(THwtjFzsEntity::getCompany, tSeatsEntity.getCorporatename()));
                if (fzsEntity != null){
                    fzsEntity.setFzsze(fzsEntity.getFzsze()+tcfzs);//分钟总数
                    fzsEntity.setSyfzs(tcfzs);//剩余分钟数
                    hwtjFzsMapper.updateById(fzsEntity);
                }

                SysUser sysUser = sysUserMapper.selectById(accountid);

                TFzsczLogEntity fzsczLog = new TFzsczLogEntity();
                fzsczLog.setUserid(sysUser.getUsername());
                fzsczLog.setGsmc(tSeatsEntity.getCorporatename());
                fzsczLog.setCztime(new Date());
                fzsczLog.setCzfzs(tcfzs);
                fzsczLog.setCzqfsyfzs(residue);

                tSeatsEntity.setResidue(tcfzs);
                //更新套餐重置时间
                Calendar calendarCZ = Calendar.getInstance();
                calendarCZ.setTime(now);
                calendarCZ.add(Calendar.DAY_OF_MONTH,  30);

                tSeatsEntity.setTccztime(calendarCZ.getTime());
                tSeatsMapper.updateById(tSeatsEntity);
                List<TSeatsEntity> tSeatsEntitiess = tSeatsMapper.selectList(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeatsEntity.getCorporatename()));
                for (TSeatsEntity t : tSeatsEntitiess) {
                    t.setResidue(tcfzs);
                    t.setTccztime(calendarCZ.getTime());
                    tSeatsMapper.updateById(t);
                }
                tFzsczLogService.save(fzsczLog);

                TCzjlEntity tCzjl = new TCzjlEntity();
                tCzjl.setUserid(sysUser.getUsername());//账号
                tCzjl.setGsmc(tSeatsEntity.getCorporatename());
                tCzjl.setCzTime(new Date());
                tCzjl.setFzs(tcfzs);
                tCzjl.setCzqk("套餐支出");
                tCzjlService.save(tCzjl);
            }
            return DataResult.success();
        } catch (Exception e){
            e.printStackTrace();
            return DataResult.fail("续费失败,请联系管理员！");
        }
    }

    @Override
    public DataResult updateEntity(TSeatsEntityOperationReqVO vo) {
        try {
            TSeatsEntity tSeats = tSeatsMapper.selectById(vo.getId());
            if (tSeats == null) {
                return addTSeats(vo);
            }
            String corporatename = tSeats.getCorporatename();
            String corporatenameVo = vo.getCorporatename();
            if (!StringUtil.equals(corporatename,corporatenameVo)){
                List<TGzszEntity> tGzszEntities = tGzszMapper.selectList(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, corporatenameVo));
                if (tGzszEntities.size()>0){
                    throw new BusinessException("修改坐席失败，该公司已存在公海规则！");
                } else {
                    //修改公司所有坐席的公司名称
                    List<TSeatsEntity> tSeatsEntities = tSeatsMapper.selectList(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, corporatename));
                    for (TSeatsEntity t : tSeatsEntities) {
                        t.setCorporatename(corporatenameVo);
                        tSeatsMapper.updateById(t);
                    }
                }
            }

            if (!StringUtil.equals(tSeats.getRole(),vo.getRole())){
                //本公司坐席数量
                Integer integer = tSeatsMapper.selectSeatCount(tSeats.getCorporatename());
                TSeatsEntity gsgl = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                        .eq(TSeatsEntity::getGsgl, "1"));
                Integer seats = Integer.valueOf(gsgl.getSeats());//坐席总数量
                String role = vo.getRole(); //角色
                SysRole byId = roleService.getById(role);
                if (StringUtils.equals("员工",byId.getName())||StringUtils.equals("主管",byId.getName())) {
                    if ( integer >= seats) {
                        throw new BusinessException("添加坐席失败，座席数已满，请联系管理员！");
                    }
                }
            }
            SysUser user = sysUserMapper.selectById(tSeats.getAccountid());
            TUserLogEntity tUserLog = new TUserLogEntity();
            tUserLog.setStart(vo.getSeats());
            tUserLog.setUsername(vo.getContacts());
            tUserLog.setUserid(vo.getAccount());
            tUserLog.setPhone(vo.getPhone());
            tUserLog.setCompany(vo.getCorporatename());
            tUserLog.setEndtime(new Date());
            //获取当前操作人
            tUserLog.setCzry(user.getUsername());
            //修改密码
            if (!Func.isEmpty(vo.getPassword())) {
                SysUser sysUser = new SysUser();
                sysUser.setId(tSeats.getAccountid());
                sysUser.setUsername(vo.getAccount());
                sysUser.setPassword(PasswordUtils.encode(vo.getPassword(), user.getSalt()));
                List<String> roles = new ArrayList<>();
                roles.add(vo.getRole());
                sysUser.setRoleIds(roles);
                if (Func.isNotEmpty(vo.getDept())) {
                    sysUser.setDeptId(vo.getDept());
                }
                sysUserMapper.updateById(sysUser);

                sysUserMapper.updateUserRole(vo.getRole(),sysUser);

            }
//            //修改账号名称
//            if (!Func.equals(user.getUsername(), vo.getAccount())&&Func.isNoneBlank(vo.getAccount())) {
//                SysUser sysUser = new SysUser();
//                sysUser.setId(tSeats.getAccountid());
//                sysUser.setUsername(vo.getAccount());
//                LambdaUpdateWrapper<SysUser> sysUserLambdaUpdateWrapper = new LambdaUpdateWrapper<SysUser>()
//                .set(SysUser::getUsername,vo.getAccount())
//                        .eq(SysUser::getId,tSeats.getAccountid());
//                sysUserMapper.update(null,sysUserLambdaUpdateWrapper);
//            }
            tSeats.setRole(vo.getRole());
            tSeats.setCorporatename(vo.getCorporatename());
            tSeats.setContacts(vo.getContacts());
            tSeats.setPhone(vo.getPhone());
            tSeats.setState(vo.getState());
            if(Func.equals(tSeats.getTcType(),"1")){
                tSeats.setResidue(vo.getResidue1());
            }
            if(Func.equals(tSeats.getTcType(),"2")){
                tSeats.setTcfzs(vo.getResidue2());//编辑的时候修改的是套餐分钟数，根据这个分钟数据重置下月的剩余分钟数
            }
            if (!Func.isEmpty(tSeats.getEndtime())) {
                Date currentDate = new Date();

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.MONTH, Integer.valueOf(tSeats.getEndtime()));
                //套餐重置时间
                Date tcczTime = calendar.getTime();
                if (Func.equals(vo.getTcType2(),"2")){
                    tSeats.setTccztime(tcczTime);
                }
            }

            tSeats.setAmount(vo.getAmount());
            tSeats.setEndtime(vo.getEndtime());


            tSeats.setMode(vo.getMode());
            tSeats.setSalesname(vo.getSalesname());
            tSeats.setPassword(vo.getPassword());

            tSeats.setLine(vo.getLine());
            tSeats.setSeats(vo.getSeats());
            tSeats.setApkid(vo.getApkid());
            tSeats.setAk(vo.getAk());
            tSeats.setSk(vo.getSk());

            if (Func.isNotEmpty(vo.getDept())) {
                tSeats.setDept(vo.getDept());
            }

            List<TSeatsEntity> tSeatsEntities = tSeatsMapper.selectList(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, vo.getCorporatename()));
            for (TSeatsEntity t : tSeatsEntities) {
                t.setLine(vo.getLine());
                updateById(t);
            }

            boolean b = this.updateById(tSeats);

//            tUserLogService.save(tUserLog);

            return DataResult.success(b);
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("编辑失败！");
        }
    }
    @Override
    public DataResult outbound(TSeatsEntityOperationReqVO vo) {
        try {
            //根据登录人查询 主叫号码、中间号
            String userId = httpSessionService.getCurrentUserId();
            SysUser sysUser = userService.getById(userId);

            List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(userId);
            List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());

            //list.contains(object);返回true说明包含,否则不包含
            List<Object> names = new ArrayList<>();
            if (collect.contains("总经理")){
                return DataResult.fail("外呼失败，角色没有外呼权限！");
            }


            TSeatsEntity tSeats = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getAccountid, userId));
            TSeatsEntity gsgl = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                    .eq(TSeatsEntity::getGsgl, "1"));
            Integer residue = gsgl.getResidue();
            String seats = tSeats.getState(); //状态  启用|禁用
            if(Func.equals("1",seats)) return DataResult.fail("外呼失败，账号已禁用请联系管理人员！");
            if (residue < 1) return DataResult.fail("外呼失败，剩余次数不足！");
            if (Func.isEmpty(gsgl)) return DataResult.fail("外呼失败，线路为空！");
            String line = gsgl.getLine();//线路
            //被叫号码
            String phoneWH = vo.getPhoneWH();

            Long integer = backlistMapper.selectCount(Wrappers.<TBacklistEntity>lambdaQuery()
                    .eq(TBacklistEntity::getPhone, phoneWH));
            if (integer>0) {
                return DataResult.fail("外呼失败，此号已经在黑名单中。");
            }

            log.info("外呼开始！！！！");
            log.info("线路："+line);
            if (Func.isEmpty(line)) return DataResult.fail("外呼失败，线路为空！");
            /**
             * 线路1 移动线路
             * 通过中间号呼叫
             */
            if (Func.equals("有销移动",line)||Func.equals("有销电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号 ---外显号码
                String xiaohao = tSeats.getPhone();
                if (Func.equals("有销移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }
                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dxline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼有销移动线路返回结果： "+body.getStr("msg")+";  状态码："+body.containsKey("code"));
                log.info("外呼有销移动线路返回结果--data： "+body.getStr("data"));
                if (!body.containsKey("code") || !"200".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("msg")+";  状态码："+body.containsKey("code"));
                    return DataResult.fail(body.getStr("msg"));
                }
                //外呼返回参数
                String sessionId = JSONUtil.parseObj(body.get("data")).getStr("sessionId");//绑定唯一 ID
                String bindNbr = JSONUtil.parseObj(body.get("data")).getStr("bindNbr");//中间号
                log.info("外呼返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(bindNbr);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态
                log.info("993 记录通话明细:{}", tThjlmxEntity.toString());
                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("msg"));//提示不对

//                TCallbakEntity c = callbakMapper.selectLLimit1();
//                c.setZjh(xiaohao);
//                c.setZjhm(phone);
//                c.setBjhm(phoneWH);
//                String bindNbr = c.getZjhm();
//                UUID uuid = UUID.randomUUID();
//                TCallbakEntity callbak = new TCallbakEntity();
//                callbak.setBindId(sessionId);//绑定 ID
//                callbak.setZjhm(bindNbr);//中间号
//                callbak.setUserid(tSeats.getId());//创建人 坐席 人
//                callbak.setCalltime(new Date());
//                callbakMapper.insert(callbak);
//                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
//                tThjlmxEntity.setBindId(sessionId);
//                tThjlmxEntity.setCtime(new Date());
//                tThjlmxEntity.setYgxm(sysUser.getUsername());
//                tThjlmxEntity.setOrg(tSeats.getDept());
//                tThjlmxEntity.setZjhm(phone);//主叫号码
//                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
//                thjlmxMapper.insert(tThjlmxEntity);
//
//                CallbackEntityVo1 r1 = new CallbackEntityVo1();
//                r1.setSessionId(uuid.toString());
//                r1.setBindNbr(c.getZjh());
//                r1.setCallerNbr(c.getZjhm());
//                r1.setCalleeNbr(c.getBjhm());
//                r1.setStartTime(c.getStartTime());
//                r1.setEndTime(c.getEndTime());
//                r1.setCallOutStartTime(c.getCallOutStartTime());
//                r1.setDuration(c.getDuration());
//                r1.setRecordUrl(c.getRecordUrl());
//                r1.setStatus(c.getStatus());
//                r1.setUlFailReason(c.getUlFailReason());
//
//                notifyurl1(r1);
//                return DataResult.success("成功");//提示不对
            }else if (Func.equals("多方移动",line) || Func.equals("多方电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号
                String xiaohao = tSeats.getPhone(); ;
                if (Func.equals("多方移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }

                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdSzcCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dyline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼多云移动线路返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                log.info("外呼多云移动线路返回结果--data： "+body.getStr("data"));
                if (!body.containsKey("code") || !"0000".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                    return DataResult.fail(body.getStr("message"));
                }
                //外呼返回参数
                String sessionId = JSONUtil.parseObj(body.get("data")).getStr("bindId");//绑定唯一 ID
                String bindNbr = JSONUtil.parseObj(body.get("data")).getStr("telX");//中间号
                log.info("外呼返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(xiaohao);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态
                log.info("1088 记录通话明细:{}", tThjlmxEntity.toString());
                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("message"));//提示不对
            } else if (Func.equals("连连移动",line) || Func.equals("连连电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号
                String xiaohao = phone ;
                if (Func.equals("连连移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }

                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdDjCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dyline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼连连移动线路返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                log.info("外呼连连移动线路返回结果--bindId： "+body.getStr("bindId"));
                if (!body.containsKey("code") || !"0".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                    return DataResult.fail(body.getStr("message"));
                }
                //外呼返回参数
                String sessionId = body.getStr("bindId");//绑定唯一 ID
                String bindNbr = body.getStr("number");//中间号
                log.info("外呼连连移动返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(xiaohao);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态

                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("message"));//提示不对
            } else if (Func.equals("好小子移动",line) || Func.equals("好小子电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号
                String xiaohao = phone ;
                if (Func.equals("好小子移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }

                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdDnCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dnline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼好小子 线路返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                log.info("外呼 好小子 线路返回结果--bindId： "+body.getStr("bindId"));
                if (!body.containsKey("code") || !"0".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("msg")+";  状态码："+body.getStr("code"));
                    return DataResult.fail(body.getStr("msg"));
                }
                /**
                 * {
                 *     "code": 0,
                 *     "msg": "success",
                 *     "data": {
                 *         "bind_id": "CR2021122255555062036389",
                 *         "number": "18577888888",
                 *         "type": 1 //直拨 2回拨
                 *     }
                 * }
                 */
                Map<String,Object> objectMap = (Map)body.get("data");

                //外呼返回参数
                String sessionId = String.valueOf(objectMap.get("bind_id"));//绑定唯一 ID
                String bindNbr = String.valueOf(objectMap.get("number"));//中间号
                log.info("外呼好小子 返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(xiaohao);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态

                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success("呼叫成功");//提示不对
            } else {
                return DataResult.fail("外呼失败，没有可用线路！");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return DataResult.fail("外呼失败，请联系管理员！");
        }
    }
    @Override
    public void deleteUser(List<String> ids) {
        tSeatsMapper.deleteUsersZjh(ids);
        tSeatsMapper.deleteUsers(ids);

        for (String id : ids) {
            TSeatsEntity seats = tSeatsMapper.selectById(id);
            SysRole role = sysRoleMapper.selectById(seats.getRole());
            boolean falg = false;
            String name = role.getName();
            if (StringUtil.equals(name,"总经理")) falg = true;
            if (falg) {
                //删除 超管角色中间号管理里面 当删除总经理账号角色后，对应的绑定也删除。
                TSeatsEntity tSeatsEntity = tSeatsMapper.selectById(id);
                List<TMiddlenumEntity> tMiddlenumEntities = tMiddlenumMapper.selectList(Wrappers.<TMiddlenumEntity>lambdaQuery().like(TMiddlenumEntity::getCompany, tSeatsEntity.getCorporatename()));
                for (TMiddlenumEntity middlenum : tMiddlenumEntities) {
                    String company = middlenum.getCompany();
                    //中间号 关联关系
                    if (company.contains(tSeatsEntity.getCorporatename())) {
                        String newCompany = company.replace(tSeatsEntity.getCorporatename()+";","");
                        middlenum.setCompany(newCompany);
                        tMiddlenumMapper.updateById(middlenum);
                    }
                }
                //删除公司设置
                tGzszMapper.delete(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            }
        }

    }
    @Override
    public void notifyurl1(CallbackEntityVo1 vo) {
//        log.info("有销回调参数: "+vo.toString());

//        log.info("有销回调参数  绑定 ID : "+vo.getSessionId());
//        log.info("有销回调参数  中间号 : "+vo.getBindNbr());
//        log.info("有销回调参数  录音地址 : "+vo.getRecordUrl());
//        log.info("有销回调参数  接通状态 2-未接通 1-已接通 : "+vo.getStatus());
//        log.info("有销回调参数  被叫接通开始时间 : "+vo.getStartTime());
//        log.info("有销回调参数  结束时间 : "+vo.getEndTime());
//        log.info("有销回调参数  主叫接通时间 : "+vo.getCallOutStartTime());
//        log.info("有销回调参数  通话时长秒 : "+vo.getDuration());
//        log.info("有销回调参数  结束状态 0-主叫挂断 1-被叫挂断 2-主叫放弃 3-被叫放弃 4-其他 : "+vo.getUlFailReason());

        //2次 回调不记录
//        TCallbakEntity callbak1 = callbakMapper.selectOne(Wrappers.<TCallbakEntity>lambdaQuery()
//                .eq(TCallbakEntity::getBindId, vo.getSessionId()));
        Date date = new Date();
//        if (callbak1 != null) date = callbak1.getCalltime();

        TCallbakTaskEntity callbakTask = new TCallbakTaskEntity();
        callbakTask.setBindId(vo.getSessionId());//绑定 ID
        callbakTask.setZjh(vo.getBindNbr());//中间号
        callbakTask.setZjhm(vo.getCallerNbr());//主叫号码
        callbakTask.setBjhm(vo.getCalleeNbr());//被叫号码
        callbakTask.setStartTime(vo.getStartTime());
        callbakTask.setEndTime(vo.getEndTime());
        callbakTask.setCallOutStartTime(vo.getCallOutStartTime());
        callbakTask.setDuration(vo.getDuration());
        callbakTask.setRecordUrl(vo.getRecordUrl());//录音地址
        callbakTask.setStatus(vo.getStatus());
        callbakTask.setUlFailReason(vo.getUlFailReason());
        callbakTask.setAddtime(date);
        callbakTask.setFlag("0");//是否更新到通话日报  0 ：否  1:是

        Calendar calendar = Calendar.getInstance();
        int minute = calendar.get(Calendar.MINUTE);
        int type =  minute % 10;

        callbakTask.setType(type);
        long start = System.currentTimeMillis();
        // 生产消息
        String jsonString = JSON.toJSONString(callbakTask);
        zSetVer.producer("callBackYXTask",jsonString);

        long end = System.currentTimeMillis();
        log.info("notifyurl1 生产消息 入库 callBackYXTask 总耗时：{} ms", end - start);

//
//        boolean save = tCallbakTaskService.save(callbakTask);
//        if (save) return;
    }

    @Override
    public void sta(List<String> ids) {
        //根据登录人
        SysUser sysUser = userService.getUserInfo();
        if(!StringUtils.equals("0",sysUser.getDeptId())){
            TSeatsEntity tSeatsEntity = tSeatsMapper.selectById(ids.get(0));
            //本公司坐席数量
            Integer integer = tSeatsMapper.selectSeatCount(tSeatsEntity.getCorporatename());
            TSeatsEntity gsgl = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeatsEntity.getCorporatename())
                    .eq(TSeatsEntity::getGsgl, "1"));
            integer += ids.size();
            Integer seats = Integer.valueOf(gsgl.getSeats());//坐席总数量
            if (integer > seats) {
                throw new BusinessException("添加坐席失败，座席数已满，请联系管理员！");
            }
        }

        tSeatsMapper.updateSta(ids,"0");
        tSeatsMapper.updateStaUser(ids,"0");
        addZhrz(ids,"0");
    }

    @Override
    public void nosta(List<String> ids) {
        tSeatsMapper.updateSta(ids,"1");
        tSeatsMapper.updateStaUser(ids,"1");
        addZhrz(ids,"1");

    }

    @Override
    public void dyline(CallbackEntityVo2 vo) {
        log.info("多云回调参数: "+vo.toString());
        if (StringUtils.equals(vo.getCallStatus(),"0")) vo.setStartTime(null);

//        log.info("多云回调参数  绑定 ID : "+vo.getBindId());
//        log.info("多云回调参数  中间号 : "+vo.getTelX());
//        log.info("多云回调参数  主叫号码 : "+vo.getTelA());
//        log.info("多云回调参数  被叫号码 : "+vo.getTelB());
//        log.info("多云回调参数  录音地址 : "+vo.getRecordUrl());
//        log.info("多云回调参数  接通状态 0-未接通 1-已接通 : "+vo.getCallStatus());
//        log.info("多云回调参数  被叫接通开始时间 : "+vo.getStartTime());
//        log.info("多云回调参数  结束时间 : "+vo.getEndTime());
//        log.info("多云回调参数  开始时间 : "+vo.getStartTime());
//        log.info("多云回调参数  通话时长秒 : "+vo.getDuration());
//        log.info("多云回调参数  结束状态 0-主叫挂断 1-被叫挂断 2-主叫放弃 3-被叫放弃 4-其他 : "+vo.getFinishStatus());



        //2次 回调不记录
//        TCallbakEntity callbak1 = callbakMapper.selectOne(Wrappers.<TCallbakEntity>lambdaQuery()
//                .eq(TCallbakEntity::getBindId, vo.getBindId()));
        Date date = new Date();
//        if (callbak1 != null) {
//            vo.setTelX(callbak1.getZjhm());
//            date = callbak1.getCalltime();
//        }
//
        TCallbakTaskEntity callbakTask = new TCallbakTaskEntity();
        callbakTask.setBindId(vo.getBindId());//绑定 ID
        callbakTask.setZjh(vo.getTelX());//中间号
        callbakTask.setZjhm(vo.getTelA());//主叫号码
        callbakTask.setBjhm(vo.getTelB());//被叫号码
        callbakTask.setStartTime(vo.getStartTime());
        callbakTask.setEndTime(vo.getEndTime());
//        callbakTask.setCallOutStartTime(vo.getCallOutStartTime());
        callbakTask.setDuration(vo.getDuration());
        callbakTask.setRecordUrl(vo.getRecordUrl());//录音地址
        callbakTask.setStatus(vo.getCallStatus());
        callbakTask.setUlFailReason(vo.getFinishStatus());
        callbakTask.setAddtime(date);
        callbakTask.setFlag("0");//是否更新到通话日报  0 ：否  1:是

        Calendar calendar = Calendar.getInstance();
        int minute = calendar.get(Calendar.MINUTE);
        int type =  minute % 10;

        callbakTask.setType(type);

        long start = System.currentTimeMillis();
        // 生产消息
        String jsonString = JSON.toJSONString(callbakTask);
        zSetVer.producer("callBackYXTask",jsonString);

        long end = System.currentTimeMillis();
        log.info("dyline 生产消息 入库 callBackYXTask 总耗时：{} ms", end - start);

//        boolean save = tCallbakTaskService.save(callbakTask);
//        if (save) return;
    }
    @Override
    public void llline(Map<String, Object>  data) {
        log.info("连连回调参数: "+data.toString());
        /**
         * ts int 必选 时间戳
         * reqId string(50) 必选 请求 UUID
         * corpKey string(50) 必选 企业账户标识 key
         * records Array          * Object         * 话单列表
         * records
         * recordId string(50) 必选 话单唯一标识
         * type string(20) 必选 通话类型：
         * OutBound_Call, 外呼电话；
         * OutBound_Unkown, 陌生外呼；
         * transferNo string(20) 必选 中间号码
         * showNo string(20) 必选 被叫方显示的号码         * 第4页共 6 页
         * result string(20) 必选 通话状态：
                             * ANSWERED, 通话成功；
                             * BUSY, 被叫忙；
                             * NO_ANSWER, 被叫无应答；
                             * REJECT, 被叫拒接；
                             * HANGUP, 主叫提前挂机；
                             * INVALID_NUMBER, 空号
                             * POWER_OFF, 关机；
                             * UNAVAILABLE, 暂时无法接听；
                             * SUSPEND, 停机；
                             * BLACK, 黑名单号码；
                             * OTHER, 其他失败情形；
                             * CALLED_RISKY, 被叫存在风险；
         * startTime string(20) 必选 通 话 开 始 时 间 格 式 yyyy-MM-dd          * HH:mm:ss
         * alertTime string(20) 被 叫 振 铃 时 间 格 式 yyyy-MM-dd          * HH:mm:ss
         * connectTime string(20) 被 叫 接 通 时 间 格 式 yyyy-MM-dd          * HH:mm:ss
         * endTime string(20) 必选 通 话 结 束 时 间 格 式 yyyy-MM-dd          * HH:mm:ss
         * duration int 必选 通话时长, 大于 0 已接通, 否则未接通
         * recordingUrl string(100) 必选 录音文件 HTTP 地址, 文件格式为 MP3（录
                             * 音格式转换有一定处理时间, 转换完成后
                             * 录音地址有效，录音托管期间地址可以访
                             * 问）；
         * callInfo string(1024) 必选 外呼绑定时的扩展字段回传信息
         * seatNo string(20) 坐席编号
         * empId string(20) 必选 员工编号
         * empNo string(20) 必选 员工号码
         * userNo string(20) 员工扩展工号
         * empNoArea string(20) 员工号码归属地
         * cusId string(20) 客户编号，外呼绑定时的客户编号回传信息
         * cusName string(20) 客户姓名，外呼绑定时的客户姓名回传信息
         * cusNo string(20) 必选 客户号码
         * cusNoArea string(20) 客户号码归属地
         * ivrInfo string(200) 语音应答内容回传
         * 内容如："{\"name\":\"满意度\",\"value\":\"满
         * 意\",\"initKey\":\"1\",\"respKey\":\"3\"}"
         * 其中 initKey 为发起键，respKey 为响应键
         */
        try{
            List<Map<String, Object>> list =  (List<Map<String, Object>>)data.get("records");
            boolean save = false;
            for(Map<String, Object> vo : list) {

                TCallbakTaskEntity callbakTask = new TCallbakTaskEntity();
                if (!StringUtils.equals(String.valueOf(vo.get("result")),"ANSWERED"))  callbakTask.setStartTime(null);

                //2次 回调不记录
                TCallbakEntity callbak1 = callbakMapper.selectOne(Wrappers.<TCallbakEntity>lambdaQuery()
                        .eq(TCallbakEntity::getBindId, String.valueOf(vo.get("recordId"))));
                Date date = new Date();
                if (callbak1 != null) {
                    vo.put("transferNo",callbak1.getZjhm());//中间号
                    date = callbak1.getCalltime();
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


                callbakTask.setBindId(String.valueOf(vo.get("callId")));//绑定 ID
//                callbakTask.setZjh(String.valueOf(vo.get("transferNo")));//中间号
            callbakTask.setZjhm(String.valueOf(vo.get("empNo")));//主叫号码
                callbakTask.setBjhm(String.valueOf(vo.get("cusNo")));//被叫号码
                callbakTask.setStartTime(sdf.parse(String.valueOf(vo.get("startTime"))));
                callbakTask.setEndTime(sdf.parse(String.valueOf(vo.get("endTime"))));
//        callbakTask.setCallOutStartTime(vo.getCallOutStartTime());
                callbakTask.setDuration(String.valueOf(vo.get("duration")));
                callbakTask.setRecordUrl(String.valueOf(vo.get("recordingUrl")));//录音地址
                callbakTask.setStatus(!StringUtils.equals(String.valueOf(vo.get("result")),"ANSWERED")?"0":"1");
//            callbakTask.setUlFailReason(String.valueOf(vo.get("recordId")));
                callbakTask.setAddtime(date);
                callbakTask.setFlag("0");//是否更新到通话日报  0 ：否  1:是

                Calendar calendar = Calendar.getInstance();
                int minute = calendar.get(Calendar.MINUTE);
                int type =  minute % 10;

                callbakTask.setType(type);

                save = tCallbakTaskService.save(callbakTask);
            }

            if (save) return;
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addZhrz(List<String> ids,String type){
        String userId = httpSessionService.getCurrentUserId();
        SysUser user = userService.getById(userId);
        for(String id: ids){
            TSeatsEntity tSeatsEntity = tSeatsMapper.selectById(id);
            SysUser byId = userService.getById(tSeatsEntity.getAccountid());
            //账号日志
            TUserLogEntity tUserLog = new TUserLogEntity();
            tUserLog.setUserid(byId.getUsername());
            tUserLog.setUsername(tSeatsEntity.getContacts());
            tUserLog.setPhone(tSeatsEntity.getPhone());
            tUserLog.setStart(type);
            tUserLog.setCompany(tSeatsEntity.getCorporatename());
            tUserLog.setEndtime(new Date());
            tUserLog.setCzry(user.getUsername());
            tUserLogService.save(tUserLog);

        }
    }
}